import React from 'react';
import * as asyncLoad from '../util/asyncLoad';
import { workflowPublicFiles } from '../constants/fileConfig';
import * as _ from '../util/public/common';
import { toJS, observable } from 'mobx'
import { observer, inject } from "mobx-react/index";
import Loading from './Loading';
import { getEcCom, getAntd, getLabel } from '../util/convert';
import {needMustInputDot} from "../util/signUtil";
import $ from 'jquery';
import './../style/form.less';

@inject('globalStore', 'layoutStore')
@observer
export default class FormSignInput extends React.Component {
    constructor() {
        super();
        this.state = { hasLoad: false, width: 0 };
    }

    componentDidMount() {
        const init = () => {
            this.setState({ hasLoad: true });
        }
        let width = $("table tbody tr:nth-child(2) td:first-child").width();
        this.setState({ "width": $("table").width() - width - 20 });
        asyncLoad.asyncLoadModule('workflowPublic', workflowPublicFiles, init);
    }

    componentDidUpdate() {
        const { hasLoad } = this.state;
        
        if (hasLoad && typeof window.REMARK_CK_REF === "undefined") {
            window.REMARK_CK_REF = this.refs.remarkCK;
            let width = $("table tbody tr:nth-child(2) td:first-child").width();
            this.setState({ "width": $("table").width() - width - 20 })
        }
    }

    contentUtil = (str) => {
        let hea = str.substr(0, str.indexOf("<div _quotoContent='true'"));
        str = str.slice(str.indexOf("<div _quotoContent='true'"));
        let pic = `[${getLabel(528760 , '图片')}]`;
        str = str.replace(/<img.*?>/g, pic)
        str = str.replace(/<[^>]*>|<\/[^>]*>/gm, "")
        str = str.replace(/\r|\n|\\s/gm, "");
        str = `<div class='remark-quote'>${str}</div>`;
        str = hea + str  + "</div>";
        return str;
    }

    // 点击删除一个签字意见
    deleteItem = (key, event) => {
        const { src } = this.props;
        const { variableMap } = this.props.globalStore;
        const remark_list_mark = src == "freeWorkflowSimple" ? "remark_list_freeWorkflowSimple" : "remark_list";
        const remark_list = variableMap.get(remark_list_mark);
        remark_list.delete(key);
    }

    //渲染引用签字意见列表
    getRemarkDom = (isInForm) => {
        const { Icon } = getAntd();
        const { variableMap } = this.props.globalStore;
        const { src } = this.props;
        const remark_list_mark = src == "freeWorkflowSimple" ? "remark_list_freeWorkflowSimple" : "remark_list";
        const remarkMap = variableMap.get(remark_list_mark) || (observable.map ? observable.map({}) : asMap({}));
        let arr = [];
        remarkMap.forEach((value, key, map) => {
            const item = <div className='remark_list_dom' style={{ position: "relative", marginLeft: isInForm ? "10px" : "0" }}>
                <div style={{ width: "100%" }} dangerouslySetInnerHTML={{ __html: this.contentUtil(value) }}></div>
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@f6g057@${key}`} type="cross" title="删除" style={{ position: "absolute", right: "10px", top: "10px", cursor: "pointer", color: "#333" }} onClick={this.deleteItem.bind(this, key)} />
            </div>
            if (toJS(value) !== '') {
                arr.push(item)
            }
        })

        return arr;
    }
    render() {
        const { WeaPopoverHrm } = getEcCom();
        const { hasLoad } = this.state;
        if (hasLoad) {
            const { WfSignInput } = window.weaWorkflowPublic;
            const { globalStore,layoutStore } = this.props;
            const { commonParam, markInfo = {}, variableMap, controlVariableMap, loadMarkInfo} = globalStore;
            const { containSignInput = false,propFileCfg } = layoutStore;
            const { onChangeEvent, onAutographBlur, isInForm = false, isPropOpenSignInput=false, src="" } = this.props;
            const isShowSignInput = variableMap.get("isShowSignInput");//签字意见
            const remark_list_mark = src == "freeWorkflowSimple" ? "remark_list_freeWorkflowSimple" : "remark_list";
            const isEditorFocus = variableMap.get('isEditorFocus');
            const remark_list = variableMap.get(remark_list_mark);
            const { requestid, requestType, intervenorright, belongTest } = commonParam;
            const { remarkInfo = {}, isHideInput, tempbeagenter, fileuserid, tempbeagentername, use_textarea_signinput,workflowRequestLogId} = markInfo;
            let   { remark } = remarkInfo;
             const isshowsigninputdiv = (requestType > 0 || intervenorright > 0) && isHideInput == '0';
            const defaultshowsigninput = isshowsigninputdiv && _.trim(remark).length > 0 || (remark_list && remark_list.size > 1)
            const isBeagent = tempbeagenter != fileuserid;
            const agent = (
                <span style={{ lineHeight: "36px", paddingLeft: "10px" }}>
                    {getLabel(388045, "您当前正在代理")}
                    <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@lvs1ya`} />
                    <a href={`javaScript:openhrm(${tempbeagenter});`} onClick={e => window.pointerXY(e)} title={tempbeagentername}><span style={{ color: "#4D7AD8", cursor: "pointer" }}>{tempbeagentername}</span></a>
                    {getLabel(84398, "进行操作")}
                </span>
            )
            //开启了提交必填，且无批注操作才显示意见必填标识
            let remarkMustInput  = needMustInputDot();
            let isopen = isShowSignInput === undefined ? defaultshowsigninput : isShowSignInput;
            if(isPropOpenSignInput) isopen = isPropOpenSignInput;
            if(propFileCfg && propFileCfg.always_show_signinput === "1")
                isopen = true;
            let className="wf-req-signInput";
            if(isopen) className += " wf-req-signInput-isOpen";
            if(remarkMustInput) className += " wf-req-signInput-mustInput";
            return (
                isInForm ?
                    <div id="remark_div">
                        <div className='wf-req-sign-input' onClick={this.initRemark} >
                            {isBeagent && agent}
                            {this.getRemarkDom(isInForm)}
                        </div>
                        <WfSignInput ecId={`${this && this.props && this.props.ecId || ''}_WfSignInput@dnyipz`}
                            ref={"remarkCK"}
                            isInForm={isInForm}
                            markInfo={markInfo}
                            requestType={requestType}
                            requestid={requestid}
                            isShowSignInput={true}
                            editorId={'remark'}
                            workflowRequestLogId={workflowRequestLogId}
                            {...remarkInfo}
                            loadReady={this.onSingInputLoadReady}
                            onChange={onChangeEvent}
                            onAutographBlur={onAutographBlur}
                            isEditorFocus={isEditorFocus}
                            controlVariableMap={controlVariableMap}
                            changeRemarkInfo={this.changeRemarkInfo}
                            saveCallBack={loadMarkInfo}
                            layout={window}
                            belongTest={belongTest}
                        />
                    </div>
                    :
                    <div id="remark_div" className={className}>
                        <div className='wf-req-sign-input'
                            style={{
                                background: !(isopen) ? "#ffffff" : "#F9F8F7",
                                cursor: !isopen ? "pointer" : "default", 
                            }}
                            onClick={src ? () => {} : this.initRemark} >
                            <i className="icon-coms-Need-feedback" style={{ marginRight: "10px", fontSize: "15px", color: "#AFAFAF ", lineHeight: "40px", display: "inline-block", verticalAlign: "bottom" }} />
                            <span style={{ color: "#A0A0A0" }}>{getLabel(17614, '签字意见')}</span>
                            {(remarkMustInput && isopen) && <span style={{ color: "red", marginLeft: "10px" }}>({getLabel(18019, "必填")})</span>}
                            <span style={{ marginLeft: "15px" }}>{isBeagent && agent}</span>
                            {this.getRemarkDom()}
                        </div>
                        <WfSignInput ecId={`${this && this.props && this.props.ecId || ''}_WfSignInput@4xn04t`} ref={"remarkCK"} markInfo={markInfo} requestType={requestType}
                            requestid={requestid}
                            isInForm={isInForm}
                            isShowSignInput={isopen}
                            editorId={src ? src :'remark'}
                            {...remarkInfo}
                            remark={this.props.remark ? this.props.remark : remark}
                            workflowRequestLogId={workflowRequestLogId}
                            loadReady={this.onSingInputLoadReady}
                            isEditorFocus={isEditorFocus}
                            controlVariableMap={controlVariableMap}
                            changeRemarkInfo={this.changeRemarkInfo}
                            saveCallBack={loadMarkInfo}
                            layout={window}
                            visible={this.props.visible}
                            belongTest={belongTest}
                        />
                    </div>
            )
        } else {
            return (<Loading ecId={`${this && this.props && this.props.ecId || ''}_Loading@1bk8be`} />);
        }
    }

    //点击签字意见，打开签字意见编辑器
    initRemark = () => {
        const { batchControlVariableMap } = this.props.globalStore;
        batchControlVariableMap({ 'isShowSignInput': true, 'isEditorFocus': true });
    }


    changeRemarkInfo = (params = {}) => {
        const { src }=this.props;
        const { changeSubmitParam,controlVariableMap } = this.props.globalStore;
        if(src == "freeWorkflowSimple"){
            controlVariableMap("freeWorkflowSimple_submitData",params)
        }else{
            changeSubmitParam(params);
        }
    }

    onSingInputLoadReady = () => {
        const { globalStore, layoutStore } = this.props;
        const { commonParam = {} } = globalStore;
        const { belongTest = false } = commonParam;
        if (belongTest) {
            try {
                parent.window.workflowAutoTestUtil.returnStatus('signInputReady');
            } catch (e) {
                if (window.console) console.log(e);
            }
        }
        
        globalStore.setBtnDisabled(false);
    }
}